package com.fengchao.api.controller.v1;

import com.alibaba.fastjson.JSON;
import com.fengchao.api.config.Constant;
import com.fengchao.api.service.TrcService;
import com.fengchao.model.entity.comm.CustomBizException;
import com.fengchao.model.entity.comm.Message;
import com.fengchao.model.entity.comm.ResponseParameter;
import com.fengchao.model.entity.comm.TokenException;
import com.fengchao.util.common.MailTools;
import com.fengchao.util.net.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static java.awt.SystemColor.info;

/**
 * 公共控制层
 * wangnian
 */
@ControllerAdvice
@RestController
public class ExceptionController {
    @Autowired
    TrcService trcService;
    @Autowired
    private MailTools mailTools;

    private static Logger logger = LoggerFactory.getLogger(ExceptionController.class);

    /**
     * 普通的提示
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomBizException.class)
    public ResponseParameter customBizExceptionHandler(CustomBizException ex) {
        ResponseParameter responseParameter = new ResponseParameter();
        responseParameter.setStatus(Message.FAILURE);
        responseParameter.setMessage(ex.getMessage());
        logger.info("响应参数:{}", JSON.toJSON(responseParameter));
        return responseParameter;
    }

    /**
     * token失效
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(TokenException.class)
    public ResponseParameter customBizExceptionHandler(TokenException ex) {
        ResponseParameter responseParameter = new ResponseParameter();
        responseParameter.setStatus(Message.TOKEN_INVALID);
        responseParameter.setMessage(ex.getMessage());
        logger.info("Token失效响应参数:{}", JSON.toJSON(responseParameter));
        return responseParameter;
    }


    /**
     * 请求的方式不对
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ResponseParameter HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        ResponseParameter responseParameter = new ResponseParameter();
        responseParameter.setStatus(Message.FAILURE);
        responseParameter.setMessage(Constant.HOSTILE_ATTACK);
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        logger.warn("请求的地址不完整=  接口地址:{},访问ip:{},异常内容:,ex:{}", httpServletRequest.getRequestURI(), IpUtil.getLocalIp(httpServletRequest), "请求的方式不对" + ex.toString());
        return responseParameter;
    }

    /**
     * 请求的参数不全
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(ServletRequestBindingException.class)
    @ResponseBody
    public ResponseParameter servletRequestBindingExceptionHandler(ServletRequestBindingException ex) {
        ResponseParameter responseParameter = new ResponseParameter();
        responseParameter.setStatus(Message.FAILURE);
        responseParameter.setMessage(Constant.PARAMETER_IS_NOT_COMPLETE);
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        logger.warn("请求的地址不完整=  接口地址:{},访问ip:{},异常内容:,ex:{}", httpServletRequest.getRequestURI(), IpUtil.getLocalIp(httpServletRequest), ex.toString());
        trcService.recordErrorLog(httpServletRequest.getRequestURI(), JSON.toJSONString(httpServletRequest.getParameterMap()), IpUtil.getLocalIp(httpServletRequest), "ServletRequestBindingException", stackMessage(ex));
        return responseParameter;
    }

    /**
     * 程序异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseParameter exceptionHandler(Exception ex) {

        ResponseParameter responseParameter = new ResponseParameter();
        responseParameter.setStatus(Message.FAILURE);
        responseParameter.setMessage(Constant.EXCEPTION);
        HttpServletRequest request1 = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        logger.error("API异常= 接口地址:{},接口参数:{},访问ip:{},异常内容:", request1.getRequestURI(), request1.getParameterMap(), request1.getRemoteHost(), ex);
//        try {
//            mailTools.SendMail("异常", "接口地址:" + request1.getRequestURI() + ",接口参数:" + JSON.toJSON(request1.getParameterMap()) + ",访问ip:" + request1.getRemoteHost() + ",异常内容:" + stackMessage(ex));
//            trcService.recordErrorLog(request1.getRequestURI(), JSON.toJSONString(request1.getParameterMap()), request1.getRemoteHost(), "Exception", stackMessage(ex));
//        } catch (Exception ex1) {
//            logger.info("异常：{}", ex1);
//        }
        return responseParameter;
    }

    //获得堆栈内容
    private String stackMessage(Exception ex) {
        StringBuffer strBuf = new StringBuffer(ex.getMessage() + "\n");
        StackTraceElement[] errors = ex.getStackTrace();
        for (StackTraceElement e : errors) {
            strBuf = strBuf.append(e.toString() + "\n");
        }
        return strBuf.toString();
    }
}
